package com.booking.springrestful.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.booking.springrestful.domain.PatternLibrary;
import com.booking.springrestful.domain.dto.PatternDto;
import com.booking.springrestful.domain.dto.PatternSaveDto;
import com.booking.springrestful.mapper.PatternLibraryMapper;
import com.booking.springrestful.resp.PageResult;
import com.booking.springrestful.service.PatternLibraryService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 13182
 * @description 针对表【pattern_library(壮锦纹样资源主库表)】的数据库操作Service实现
 * @createDate 2025-10-15 13:24:53
 */
@Service
public class PatternLibraryServiceImpl extends ServiceImpl<PatternLibraryMapper, PatternLibrary>
        implements PatternLibraryService {

    @Override
    public PageResult<PatternSaveDto> getPatternList(PatternDto dto) {
        // 1. 构造分页对象（MyBatis-Plus Page 从 1 开始）
        Page<PatternLibrary> page = new Page<>(dto.getCurrent(), dto.getPageSize());

        // 2. 构造查询条件
        LambdaQueryWrapper<PatternLibrary> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(dto.getType())) {
            queryWrapper.eq(PatternLibrary::getType, dto.getType());
        }
        if (StringUtils.hasText(dto.getRegion())) {
            queryWrapper.like(PatternLibrary::getRegion, dto.getRegion());
        }
        if (StringUtils.hasText(dto.getDifficultyLevel())) {
            queryWrapper.eq(PatternLibrary::getDifficultyLevel, dto.getDifficultyLevel());
        }
        if (StringUtils.hasText(dto.getStatus())) {
            queryWrapper.eq(PatternLibrary::getStatus, dto.getStatus());
        }

        // 3. 执行分页查询
        IPage<PatternLibrary> result = this.page(page, queryWrapper);

        // 4. 转换为 DTO 列表
        List<PatternSaveDto> dtoList = result.getRecords().stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());

        // 5. 构造你定义的 PageResult
        PageResult<PatternSaveDto> pageResult = new PageResult<>();
        pageResult.setTotal(result.getTotal());
        pageResult.setData(dtoList);

        return pageResult;
    }

    @Override
    public void savePattern(PatternSaveDto dto) {
        PatternLibrary entity = convertToEntity(dto);
        this.save(entity);
    }

    @Override
    public void updatePattern(PatternSaveDto dto) {
        PatternLibrary entity = convertToEntity(dto);
        this.updateById(entity);
    }

    @Override
    public void deletePatterns(List<Long> ids) {
        ids.forEach(item->{
            PatternSaveDto byId = this.getPatternById(item);
            if (Objects.equals(byId.getStatus(), "正常")){
                throw new RuntimeException("纹样启用中不可删除");
            }
            this.removeById(item);
        });
    }

    @Override
    public PatternSaveDto getPatternById(Long id) {
        PatternLibrary entity = this.getById(id);
        if (entity == null) {
            throw new RuntimeException("纹样不存在");
        }
        return convertToDto(entity);
    }

    // ==================== 工具方法：Entity ↔ DTO ====================

    private PatternSaveDto convertToDto(PatternLibrary entity) {
        if (entity == null) return null;
        PatternSaveDto dto = new PatternSaveDto();
        dto.setId(entity.getId());
        dto.setName(entity.getName());
        dto.setType(entity.getType());
        dto.setRegion(entity.getRegion());
        dto.setDifficultyLevel((String) entity.getDifficultyLevel());
        dto.setCulturalMeaning(entity.getCulturalMeaning());
        dto.setHistoricalBackground(entity.getHistoricalBackground());
        dto.setCraftProcess(entity.getCraftProcess());
        dto.setTemplateFilePath(entity.getTemplateFilePath());
        dto.setStatus((String) entity.getStatus());
        dto.setPatternRole((String) entity.getPatternRole());
        return dto;
    }

    private PatternLibrary convertToEntity(PatternSaveDto dto) {
        if (dto == null) return null;
        PatternLibrary entity = new PatternLibrary();
        entity.setId(dto.getId());
        entity.setName(dto.getName());
        entity.setType(dto.getType());
        entity.setRegion(dto.getRegion());
        entity.setDifficultyLevel(dto.getDifficultyLevel());
        entity.setCulturalMeaning(dto.getCulturalMeaning());
        entity.setHistoricalBackground(dto.getHistoricalBackground());
        entity.setCraftProcess(dto.getCraftProcess());
        entity.setTemplateFilePath(dto.getTemplateFilePath());
        entity.setStatus(dto.getStatus());
        entity.setPatternRole(dto.getPatternRole());
        return entity;
    }
}